unit View_Main;

interface

uses
  StateMachine,

  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.MPlayer,
  Vcl.StdCtrls, Vcl.ComCtrls;

type
  TMainView = class( TForm )
    MediaPlayer1 : TMediaPlayer;
    Button1 : TButton;
    Memo1 : TMemo;
    Memo2 : TMemo;
    ProgressBar1 : TProgressBar;
    procedure MediaPlayer1Notify( Sender : TObject );
    procedure Button1Click( Sender : TObject );
    procedure FormCreate( Sender : TObject );
    procedure FormDestroy( Sender : TObject );
  private
    FStateMachine : TStateMachine;
    procedure PlaySound( const AFileName : string = '' );
    procedure StepEvent( Sender : TObject; const AText : string; AState : TState );
  public

  end;

var
  MainView : TMainView;

implementation

{$R *.dfm}

uses
  Winapi.SHFolder;

function GetSystemRoot : string;
var
  LStr : array [0 .. MAX_PATH] of Char;
begin
  SetLastError( ERROR_SUCCESS );

  if SHGetFolderPath( 0, CSIDL_WINDOWS, 0, 0, @LStr ) = S_OK
  then
    Result := LStr;
end;

procedure TMainView.Button1Click( Sender : TObject );
begin
  FStateMachine.Text := Memo2.Text;
  FStateMachine.Step;
end;

procedure TMainView.FormCreate( Sender : TObject );
begin
  FStateMachine        := TStateMachine.Create;
  FStateMachine.OnStep := StepEvent;
end;

procedure TMainView.FormDestroy( Sender : TObject );
begin
  FStateMachine.Free;
end;

procedure TMainView.MediaPlayer1Notify( Sender : TObject );
var
  LMediaPlayer : TMediaPlayer;
begin
  LMediaPlayer := Sender as TMediaPlayer;

  if LMediaPlayer.Position = LMediaPlayer.Length
  then
    begin
      FStateMachine.Step;
    end;
end;

procedure TMainView.PlaySound( const AFileName : string );
begin

  if ( MediaPlayer1.FileName <> AFileName ) and FileExists( AFileName )
  then
    begin
      MediaPlayer1.Close;
      MediaPlayer1.FileName := AFileName;
    end;
  MediaPlayer1.Open;
  MediaPlayer1.Position := 0;
  MediaPlayer1.Play;
end;

procedure TMainView.StepEvent( Sender : TObject; const AText : string; AState : TState );
begin
  case AState of
    sLetter :
      PlaySound( GetSystemRoot + '\Media\Windows Information Bar.wav' );
    sBlank :
      PlaySound( GetSystemRoot + '\Media\Windows Default.wav' );
    sCR :
      PlaySound( GetSystemRoot + '\Media\Speech On.wav' );
    sLF :
      PlaySound( GetSystemRoot + '\Media\Windows Balloon.wav' );
    sFinish :
      PlaySound( GetSystemRoot + '\Media\tada.wav' );
  end;
  Memo1.Text            := AText;
  ProgressBar1.Position := ( Sender as TStateMachine ).Position;
  ProgressBar1.Max      := ( Sender as TStateMachine ).Max;
end;

end.
